package com.customization.unionpay.market.util;

import com.alibaba.fastjson.JSONObject;
import weaver.integration.logging.Logger;
import weaver.integration.logging.LoggerFactory;

import java.security.SecureRandom;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

/**
 * @author sjm
 * @description 创新结算系统相关
 */
public class InnovativeSettlementUtils {

    private static final Logger log = LoggerFactory.getLogger(InnovativeSettlementUtils.class);

    private static Random rand;

    static {
        try{
            rand = SecureRandom.getInstanceStrong();
        }catch(Exception e){
            log.info("初始化随机数异常:"+e.getMessage());
        }
    }


    /**
     * 创建资金划付
     * @param mpmKey
     * @return
     */
    public static String createWorkFlow(JSONObject mpmKey) throws Exception {
        String innovativeCreateWorkflowUrl = com.customization.unionpay.market.util.PropUtils.BB_LOG.getPropValue("marketSubject", "innovativeCreateWorkflowUrl");
        String innovativeServiceId = com.customization.unionpay.market.util.PropUtils.BB_LOG.getPropValue("marketSubject", "innovativeServiceId");
        JSONObject params = commonParams(innovativeCreateWorkflowUrl);
        params.put("req",mpmKey);
        log.info("创建资金划付-推送创新结算参数："+params);
        return MagpieUtils.getCreateSystemSettlement(params, innovativeServiceId);
    }

    /**
     * 查询付款状态
     * @param mpmKeyList
     * @return
     */
    public static String queryPayState(JSONObject mpmKeyList) throws Exception {
        String innovativeGetPayStateUrl = com.customization.unionpay.market.util.PropUtils.BB_LOG.getPropValue("marketSubject", "innovativeGetPayStateUrl");
        String innovativeServiceId = com.customization.unionpay.market.util.PropUtils.BB_LOG.getPropValue("marketSubject", "innovativeServiceId");
        JSONObject params = commonParams(innovativeGetPayStateUrl);
        params.put("req",mpmKeyList);
        log.info("查询付款状态-推送创新结算参数："+params);
        return MagpieUtils.getCreateSystemSettlement(params, innovativeServiceId);
    }

    /**
     * 公共参数
     * @param apiName
     * @return
     */
    private static JSONObject commonParams(String apiName){
        String innovativeSysCode = com.customization.unionpay.market.util.PropUtils.BB_LOG.getPropValue("marketSubject", "innovativeSysCode");
        String tokenId = PropUtils.BB_LOG.getPropValue("marketSubject", "innovativeTokenId");
        JSONObject params = new JSONObject();
        params.put("v","1.0");
        params.put("sys",innovativeSysCode);
        String date = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        String sixNumber = String.valueOf(rand.nextInt(900000) + 100000);
        String id = innovativeSysCode+date+sixNumber;
        params.put("id",id);
        params.put("apiName",apiName);
        params.put("tokenId",tokenId);
        return params;
    }

}
